package cn.edu.gdgm.system.controller;

import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.edu.gdgm.system.dto.Result;
import cn.edu.gdgm.system.config.WxMaConfiguration;
import cn.edu.gdgm.system.dto.UserParamDto;
import cn.edu.gdgm.system.entity.User;
import cn.edu.gdgm.system.service.IUserService;
import cn.fightingguys.security.web.wechat.entity.WeChatMiniProgramUserDetails;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author quan
 * @date 2021-03-06
 */
@Api(tags = {"用户Controller"})
@RestController
@RequestMapping("/user")
public class UserController {
    public static final String LOGIN_URL = "http://localhost:8080/user/wxLogin";

    @Resource
    private IUserService userService;

    @Resource
    private WxMaConfiguration wxMaConfiguration;

    @PostMapping("/login")
    @ApiOperation(value = "获取token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jsCode", value = "wx.login的jsCode")
    })
    public String login(@RequestParam String jsCode, HttpServletResponse response) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> req = new LinkedMultiValueMap<>();
        req.add("jsCode", jsCode);
        try {
            ResponseEntity<HashMap> resp = restTemplate.postForEntity(LOGIN_URL, req, HashMap.class);
            HashMap body = resp.getBody();
            if (body != null && body.containsKey("token")) {
                return "WxToken " + body.get("token");
            }
            return "login failed";
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(400);
            return "login exception";
        }
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    @PreAuthorize("hasAuthority('Verified')")
    public Result register(@ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails, UserParamDto userParamDto) {
        User user = new User();
        user.setWechatOpenId(userDetails.getOpenId());
        user.setFirstJoinDate(LocalDateTime.now());
        if (userParamDto.getEncryptedData() != null && userParamDto.getIv() != null) {
            WxMaUserService userService = wxMaConfiguration.wxMpService().getUserService();
            WxMaPhoneNumberInfo phoneNoInfo = userService.getPhoneNoInfo(userDetails.getSessionKey(), userParamDto.getEncryptedData(), userParamDto.getIv());
            String phoneNumber = phoneNoInfo.getPhoneNumber();
            user.setVerifyPhone(phoneNumber);
        }
        return toResult(userService.save(user));
    }


    @GetMapping
    @ApiOperation(value = "查询当前用户信息")
    public Result findOne(@ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        String openId = userDetails.getOpenId();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_open_id", openId);
        return Result.success(userService.getOne(queryWrapper));
    }


    private Result toResult(boolean b) {
        if (b) {
            return Result.success("操作成功");
        } else {
            return Result.error(201, "操作失败");
        }
    }

}
